package com.vca.service.service.Impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.vca.common.constants.Constants;
import com.vca.common.constants.OrderRedisConstans;
import com.vca.common.model.order.StoreOrder;
import com.vca.common.model.order.StoreOrderInfo;
import com.vca.common.model.sms.SmsTemplate;
import com.vca.common.model.system.SystemNotification;
import com.vca.common.model.user.User;
import com.vca.common.model.user.UserToken;
import com.vca.common.request.OrderPayRequest;
import com.vca.common.response.OrderPayResultResponse;
import com.vca.common.utils.RedisUtil;
import com.vca.service.service.*;
import lombok.Data;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;


/**
 * OrderPayService 实现类
 */
@Data
@Service
public class OrderPayServiceImpl implements OrderPayService {

    public static final Logger logger = LoggerFactory.getLogger(OrderPayServiceImpl.class);

    @Autowired
    private TemplateMessageService templateMessageService;

    @Autowired
    private UserTokenService userTokenService;

    @Autowired
    private StoreOrderInfoService storeOrderInfoService;

    @Autowired
    private UserService userService;

    @Autowired
    private SystemNotificationService systemNotificationService;

    @Autowired
    private EmailTemplateService emailTemplateService;

    @Autowired
    private SmsTemplateService smsTemplateService;

    @Autowired
    private SystemConfigService systemConfigService;

    @Autowired
    private SmsService smsService;

    @Autowired
    private RedisUtil redisUtil;

    /**
     * 支付成功处理
     *
     * @param storeOrder 订单
     */
    @Override
    public Boolean paySuccess(StoreOrder storeOrder) {
        try {
            switch (storeOrder.getType()) {
                // TODO: 2022/12/29 课程订单
                case 0:
                    generateMessageOfEvent("课程", storeOrder);
                    break;
                // TODO: 2022/12/29 套课订单
                case 1:
                    generateMessageOfEvent("套课", storeOrder);
                    break;
                // TODO: 2022/12/29 讲座订单
                case 2:
                    generateMessageOfEvent("讲座", storeOrder);
                    break;
                // TODO: 2022/12/29 展览订单
                case 3:
                    generateMessageOfEvent("展览", storeOrder);
                    break;
                // TODO: 2022/12/29 商品订单
                case 4:
                    generateMessageOfProduct(storeOrder);
                    break;
                default:
                    break;
            }
        } catch (Exception e) {
            return false;
        }
        return true;
    }

    private void generateMessageOfProduct(StoreOrder storeOrder) throws Exception {
        SystemNotification paySuccessOfProduct = systemNotificationService.getByMark(OrderRedisConstans.PAY_SUCCESS_OF_PRODUCT);
        if (paySuccessOfProduct.getIsRoutine().equals(1)) {
            generateTemplateOfPaySuccessRoutine(storeOrder, paySuccessOfProduct.getRoutineId());
        }
        if (paySuccessOfProduct.getIsWechat().equals(1)) {
            // TODO: 2023/1/3 公众号模板消息
            HashMap<String, Object> message = new HashMap<>();
            message.put("first", "您好，您有新的订单提交");
            message.put("keyword1", storeOrder.getOrderId());
            message.put("keyword2", userService.getById(storeOrder.getUid()).getNickname());
            message.put("keyword3", String.format("%.2f", storeOrder.getPayPrice()));
            message.put("keyword4", DateUtil.format(storeOrder.getPayTime(), Constants.DATE_FORMAT));
            message.put("remark", "您有新的商品订单了，请去小程序上查收。");
            UserToken userToken = userTokenService.getTokenByUserIdException(storeOrder.getUid(), OrderRedisConstans.SYSTEM_TYPE_ROUTINE);
            if (userToken != null) {
                templateMessageService.pushTemplatePublicMessage("pages/user-order-details/index?orderNo=" + storeOrder.getOrderId(),
                        paySuccessOfProduct.getWechatId(), message, userToken.getToken());
            }
        }
        if (paySuccessOfProduct.getIsSms().equals(1)) {
            // TODO: 2023/1/3 发送短信
            SmsTemplate smsTemplate = smsTemplateService.getDetail(paySuccessOfProduct.getSmsId());
            User user = userService.getById(storeOrder.getUid());
            smsService.sendPaySuccess("product", null, storeOrder.getPayPrice(), storeOrder.getOrderId(), user.getPhone(), smsTemplate.getTempId()
                    , "pages/user-order-details/index?orderNo=" + storeOrder.getOrderId());
        }
    }

    /**
     * @Description:支付成功处理生成订单消息
     * @author:chenbing
     * @date 2023/1/3 11:07
     */
    private void generateMessageOfEvent(String type, StoreOrder storeOrder) throws Exception {
        SystemNotification paySuccessOfEvent = systemNotificationService.getByMark(OrderRedisConstans.PAY_SUCCESS_OF_EVENT);
        List<StoreOrderInfo> orderInfoList = storeOrderInfoService.list(new LambdaQueryWrapper<StoreOrderInfo>().eq(StoreOrderInfo::getOrderNo, storeOrder.getOrderId()));
        StoreOrderInfo orderInfo = orderInfoList.get(0);
        if (paySuccessOfEvent.getIsRoutine().equals(1)) {
            generateTemplateOrPaySuccessRoutine(type, storeOrder, paySuccessOfEvent.getRoutineId());
        }
        if (paySuccessOfEvent.getIsWechat().equals(1)) {
            // TODO: 2023/1/3 公众号模板消息
            HashMap<String, Object> message = new HashMap<>();
            message.put("first", "预约成功提醒");
            message.put("keyword1", userService.getById(orderInfo.getBuyer()).getNickname());
            message.put("keyword2", cn.hutool.core.date.DateUtil.format(new Date(), Constants.DATE_FORMAT));
            message.put("keyword3", "预约成功");
            message.put("remark", "请耐心等待门店的安排，留意最新通知。");
            generateTemplateOrPaySuccessPublic(message, paySuccessOfEvent.getWechatId(), storeOrder);
        }
        if (paySuccessOfEvent.getIsSms().equals(1)) {
            // TODO: 2023/1/3 发送短信
            SmsTemplate smsTemplate = smsTemplateService.getDetail(paySuccessOfEvent.getSmsId());
            if (Objects.equals(orderInfo.getBuyer(), orderInfo.getLecturer())) {
                smsPaySuccessEvent(orderInfo.getBuyer(), orderInfo, storeOrder, smsTemplate.getTempId());
            } else {
                smsPaySuccessEvent(orderInfo.getBuyer(), orderInfo, storeOrder, smsTemplate.getTempId());
                smsPaySuccessEvent(orderInfo.getLecturer(), orderInfo, storeOrder, smsTemplate.getTempId());
            }
        }
    }

    private void generateTemplateOrPaySuccessPublic(HashMap<String, Object> message, Integer wechatId, StoreOrder storeOrder) {
        List<StoreOrderInfo> orderInfoList = storeOrderInfoService.list(new LambdaQueryWrapper<StoreOrderInfo>().eq(StoreOrderInfo::getOrderNo, storeOrder.getOrderId()));
        String pageUrl = "pages/user-order-details/index?orderNo=" + storeOrder.getOrderId();
        UserToken buyerToken = null;
        if (ObjectUtil.isNotNull(orderInfoList.get(0).getBuyer())) {
            buyerToken = userTokenService.getTokenByUserId(orderInfoList.get(0).getBuyer(), OrderRedisConstans.SYSTEM_TYPE_ROUTINE);
        }
        UserToken lecturerToken = null;
        if (ObjectUtil.isNotNull(orderInfoList.get(0).getLecturer())) {
            lecturerToken = userTokenService.getTokenByUserId(orderInfoList.get(0).getLecturer(), OrderRedisConstans.SYSTEM_TYPE_ROUTINE);
        }
        if (Objects.equals(orderInfoList.get(0).getBuyer(), orderInfoList.get(0).getLecturer())) {
            if (ObjectUtil.isNotNull(buyerToken)) {
                templateMessageService.pushTemplatePublicMessage(pageUrl, wechatId, message, buyerToken.getToken());
            }
        } else {
            if (ObjectUtil.isNotNull(buyerToken)) {
                templateMessageService.pushTemplatePublicMessage(pageUrl, wechatId, message, buyerToken.getToken());
            }
            if (ObjectUtil.isNotNull(lecturerToken)) {
                templateMessageService.pushTemplatePublicMessage(pageUrl, wechatId, message, lecturerToken.getToken());
            }
        }
    }


    /**
     * @Description:支付成功生成短信模板
     * @author:chenbing
     * @date 2023/1/4 10:22
     */
    public void smsPaySuccessEvent(Integer userId, StoreOrderInfo orderInfo, StoreOrder storeOrder, String tempId) {
        if (ObjectUtil.isNotNull(userId)) {
            User user = userService.getById(userId);
            if (ObjectUtil.isNotNull(user.getPhone())) {
                smsService.sendPaySuccess("event", orderInfo.getName(), null, null, user.getPhone(), tempId, "pages/user-order-details/index?orderNo=" + storeOrder.getOrderId());
            }
        } else {
            smsService.sendPaySuccess("event", orderInfo.getName(), null, null, orderInfo.getLecturerPhone(), tempId, "pages/user-order-details/index?orderNo=" + storeOrder.getOrderId());
        }
    }

    /**
     * @Description:生成课程/套课/讲座/展览预约成功订阅消息
     * @author:chenbing
     * @date 2022/12/29 18:24
     */
    public HashMap<String, String> generateTemplateOrPaySuccessRoutine(String type, StoreOrder order, Integer routineId) {
        //预约类型{{thing2.DATA}}预约状态{{phrase3.DATA}}提交时间{{time4.DATA}}温馨提醒{{thing5.DATA}}
        HashMap<String, String> messageMap = new HashMap<>();
        messageMap.put("thing2", type);
        messageMap.put("phrase3", "预约成功");
        messageMap.put("time4", DateUtil.format(order.getPayTime(), "yyyy年MM月dd日 HH:mm"));
        messageMap.put("thing5", "邀您一同在历峰双子别墅探索新知。");
        String pageUrl = "pages/user-order-details/index?orderNo=" + order.getOrderId();
        List<StoreOrderInfo> orderInfoList = storeOrderInfoService.list(new LambdaQueryWrapper<StoreOrderInfo>().eq(StoreOrderInfo::getOrderNo, order.getOrderId()));
        UserToken buyerToken = null;
        if (ObjectUtil.isNotNull(orderInfoList.get(0).getBuyer())) {
            buyerToken = userTokenService.getTokenByUserId(orderInfoList.get(0).getBuyer(), OrderRedisConstans.SYSTEM_TYPE_ROUTINE);
        }
        UserToken lecturerToken = null;
        if (ObjectUtil.isNotNull(orderInfoList.get(0).getLecturer())) {
            lecturerToken = userTokenService.getTokenByUserId(orderInfoList.get(0).getLecturer(), OrderRedisConstans.SYSTEM_TYPE_ROUTINE);
        }
        if (Objects.equals(orderInfoList.get(0).getBuyer(), orderInfoList.get(0).getLecturer())) {
            if (ObjectUtil.isNotNull(buyerToken)) {
                templateMessageService.pushMiniTemplateMessage(routineId, messageMap, buyerToken.getToken(), pageUrl);
            }
        } else {
            if (ObjectUtil.isNotNull(buyerToken)) {
                templateMessageService.pushMiniTemplateMessage(routineId, messageMap, buyerToken.getToken(), pageUrl);
            }
            if (ObjectUtil.isNotNull(lecturerToken)) {
                templateMessageService.pushMiniTemplateMessage(routineId, messageMap, lecturerToken.getToken(), pageUrl);
            }
        }
        return messageMap;
    }

    /**
     * @Description:生成商品支付成功订阅消息
     * @author:chenbing
     * @date 2022/12/30 10:35
     */
    public HashMap<String, String> generateTemplateOfPaySuccessRoutine(StoreOrder order, Integer routineId) throws Exception {
        //订单编号{{character_string5.DATA}}下单金额{{amount3.DATA}}下单时间{{date1.DATA}}温馨提示{{thing7.DATA}}
        HashMap<String, String> messageMap = new HashMap<>();
        messageMap.put("character_string5", order.getOrderId());
        messageMap.put("amount3", String.valueOf(order.getPayPrice()));
        messageMap.put("date1", DateUtil.format(order.getPayTime(), "yyyy年MM月dd日"));
        messageMap.put("thing7", "邀您一同在历峰双子别墅探索新知。");
        UserToken userToken = userTokenService.getTokenByUserIdException(order.getUid(), OrderRedisConstans.SYSTEM_TYPE_ROUTINE);
        if (userToken != null) {
            templateMessageService.pushMiniTemplateMessage(routineId, messageMap, userToken.getToken(), "pages/user-order-details/index?orderNo=" + order.getOrderId());
        }
        return messageMap;
    }

    /**
     * 订单支付
     *
     * @param orderPayRequest 支付参数
     * @param ip              ip
     * @return OrderPayResultResponse
     */
    @Override
    public OrderPayResultResponse payment(OrderPayRequest orderPayRequest, String ip) {
        return null;
    }
}
